﻿using System.Collections.Generic;
using System.ComponentModel.Composition;
using Roslyn.Compilers.Common;
using Roslyn.Compilers.CSharp;
using RoslynCompiler.MEF;

namespace OperatorGenericConstraint
{
    [Export(typeof(ICodeRewriter))]
    public class OperatorGenericConstraintCodeRewriter : ICodeRewriter
    {
        private Dictionary<MethodDeclarationSyntax, List<SyntaxKind>> _methodsWithOperators = new Dictionary<MethodDeclarationSyntax, List<SyntaxKind>>();

        public SyntaxNode Rewrite(SyntaxNode originalNode, int rewriterIndex, ISemanticModel semanticModel)
        {
            switch (rewriterIndex)
            {
                case 0:
                    List<OperatorGenericConstraintAnnotation> parameterizedNewGenericConstraintAnnotation = new List<OperatorGenericConstraintAnnotation>();
                    var value = new MethodOperatorsGenericConstraintRewriter(semanticModel, parameterizedNewGenericConstraintAnnotation).Visit((SyntaxNode)originalNode);
                    foreach (var newGenericConstraintAnnotation in parameterizedNewGenericConstraintAnnotation)
                        foreach (MethodDeclarationSyntax methodWithOperator in value.GetAnnotatedNodesAndTokens(newGenericConstraintAnnotation))
                            _methodsWithOperators.Add(methodWithOperator, newGenericConstraintAnnotation.Operators);
                    return value;
                case 1:
                    return new GenericMethodCallRewriter(semanticModel, _methodsWithOperators).Visit(originalNode);
            }
            return originalNode;
        }

        public int RewriterCount
        {
            get { return 2; }
        }
    }
}
